import datetime
import re
from enetity_extraction.test import get_extraction_results

def convert_date_to_datetime(date_str):
    # 将中文数字转换为阿拉伯数字并格式化日期
    chinese_to_digit = {
        '〇': '0', '一': '1', '二': '2', '三': '3', '四': '4',
        '五': '5', '六': '6', '七': '7', '八': '8', '九': '9'
    }
    # 替换年份部分
    try:
        year = ''.join(chinese_to_digit[char] for char in date_str[:4])
    except Exception as e:
        return None

    # 查找月份部分
    month_start = date_str.find('年') + 1
    month_end = date_str.find('月')
    month_str = date_str[month_start:month_end]

    month_multi = 1
    month_total = 0
    if month_str[0] != '十':
        month_multi = int(chinese_to_digit[month_str[0]])
    for i in range(len(month_str)):
        if month_str[i] == '十':
            month_total = 0
            month_total = month_total + month_multi * 10
            month_multi = 1
        else:
            month_multi = int(chinese_to_digit[month_str[i]])
            month_total = month_total + int(chinese_to_digit[month_str[i]])

    # 查找日期部分
    day_start = month_end + 1
    day_end = date_str.find('日')
    day_str = date_str[day_start:day_end]

    data_multi = 1
    data_total = 0
    if day_str[0] != '十':
        data_multi = int(chinese_to_digit[day_str[0]])
    for i in range(len(day_str)):
        if day_str[i] == '十':
            data_total = 0
            data_total = data_total + data_multi * 10
            data_multi = 1
        else:
            data_multi = int(chinese_to_digit[day_str[i]])
            data_total = data_total + int(chinese_to_digit[day_str[i]])

    # if (day_end - day_start) == 3:
    #
    #     day = f"{chinese_to_digit[day_str[0]]}{chinese_to_digit[day_str[-1]]}"
    # elif (day_end - day_start) == 2:
    #     if day_str[-1] == '十':
    #         day = f"{chinese_to_digit[day_str[0]]}{'0'}"
    #     else:

    # 构建阿拉伯数字格式的日期字符串
    date_str = f"{year}-{str(month_total)}-{str(data_total)}"
    # 尝试将字符串解析为日期对象,如果是不合法日期（例如，2024-02-30），
    # 则 datetime.strptime 会引发 ValueError 异常，导致 except 块执行并返回 None。
    datetime = None
    try:
        datetime = datetime.datetime.strptime(date_str, "%Y-%m-%d")
    except Exception as e:
        datetime = None

    return datetime



def check_date_logic(article_sections, extract_sections):
    # json_data = get_extraction_results(file_path)
    # 提取日期
    filing_date = None
    trial_date = None
    intermediate_dates = None
    if '收案年度' in extract_sections and 'match' in extract_sections['收案年度'] and len(extract_sections['收案年度']['match']) == 4:
        filing_date_str = extract_sections['收案年度']['match'] + "年01月01日"
        filing_date_str = re.sub(r'年|月|日', '-', filing_date_str)[:len(filing_date_str)-1]
        extract_sections_copy=extract_sections['收案年度'].copy()
        try:
            extract_sections_copy['match'] = datetime.datetime.strptime(filing_date_str, "%Y-%m-%d")
        except Exception as e:
            extract_sections_copy['match'] = None
        filing_date = extract_sections_copy['match']
    # filing_date_str = '2018' + "年01月01日"
    if '审判时间' in extract_sections and 'match' in extract_sections['审判时间']:
        trial_date_str = extract_sections['审判时间'].copy()
        trial_date_str['match'] = convert_date_to_datetime(trial_date_str['match'])
        trial_date = trial_date_str['match']
    if '中间日期' in extract_sections and len(extract_sections['中间日期']) > 0:
        intermediate_dates = []
        for intermediate_date in extract_sections['中间日期']:
            try:
                intermediate_dates_str = re.sub(r'年|月|日', '-', intermediate_date['match'])[:(len(intermediate_date['match'])-1)]
                intermediate_date['match'] = datetime.datetime.strptime(intermediate_dates_str, "%Y-%m-%d")
            except Exception as e:
                continue
            intermediate_dates.append(intermediate_date['match'])
    # 转换日期为 datetime 对象
    # filing_date = datetime.datetime.strptime(filing_date_str, "%Y-%m-%d")
    # trial_date = convert_date_to_datetime(trial_date_str)
    # intermediate_dates = [datetime.datetime.strptime(date, "%Y-%m-%d") for date in intermediate_dates_str]

    # 初始化错误列表
    errors = []
    filing_trial_errors = []
    filing_inter_errors = []
    trial_inter_errors = []
    # 检查立案日期和审判日期
    if filing_date is not None and trial_date is not None and filing_date > trial_date:
        error_info = {
            "correct": "",
            "desc": "",
            "start": trial_date['start_pos'],
            "end": trial_date['end_pos'],
            "exception": "False",
            "explain": "",
            "label": "",
            "label_type": "",
            "offset": trial_date['end_pos']-trial_date['start_pos']+1,
            "opt": "",
            "ppl": "",
            "pre_insert": "",
            "source": "",
            "tag": "",
            "text": "",
            "type": f"立案日期{filing_date['match']}晚于审判日期{trial_date['match']}",
            "url": "",
            "word": "",
            # "paragraph_index": trial_date['paragraph_index']
        }
        filing_trial_errors.append(error_info)


    # 检查立案日期和案情描述日期
    if intermediate_dates is not None:
        """
        for date in intermediate_dates:
            if filing_date is not None and date is not None and filing_date < date:
                error_info = {
                    "correct": "立案日期应晚于案情描述日期",
                    "desc": "立案日期早于某个案情描述日期",
                    "start": None,
                    "end": None,
                    "exception": "False",
                    "explain": f"立案日期{filing_date_str}早于案情描述日期{date.strftime('%Y年%m月%d日')}",
                    "label": 2,
                    "label_type": 0,
                    "offset": None,
                    "opt": "修正日期",
                    "ppl": "10000",
                    "pre_insert": 1,
                    "source": "立案日期与案情描述日期逻辑错误",
                    "tag": "",
                    "text": "",
                    "type": "日期逻辑错误",
                    "url": "",
                    "word": f"立案日期{filing_date_str}早于案情描述日期{date.strftime('%Y年%m月%d日')}"
                }
                filing_inter_errors.append(error_info)
        """

        # 检查案情描述日期和审判日期
        for date in intermediate_dates:
            if date is not None and trial_date is not None and date > trial_date:
                error_info = {
                    "correct": "",
                    "desc": "",
                    "start": trial_date['start_pos'],
                    "end": trial_date['end_pos'],
                    "exception": "",
                    "explain": "",
                    "label": "",
                    "label_type": "",
                    "offset": trial_date['end_pos']-trial_date['start_pos']+1,
                    "opt": "",
                    "ppl": "",
                    "pre_insert": "",
                    "source": "",
                    "tag": "",
                    "text": "",
                    "type": f"案情描述日期{date['match']}晚于审判日期{trial_date['match']}",
                    "url": "",
                    "word": "",
                    # "paragraph_index": trial_date['paragraph_index']
                }
                trial_inter_errors.append(error_info)
    errors.extend(filing_trial_errors)
    errors.extend(filing_inter_errors)
    errors.extend(trial_inter_errors)
    return {"data": errors}

if __name__=="__main__":
    filename = '/Users/hoyo/PycharmProjects/judicial_document_proofreading/enetity_extraction/0725_test_data/2-贵州林荣资产管理有限公司与刘正超、周相波民间借贷纠纷一审民事案141382473.txt'
    # 执行日期逻辑检查
    result = check_date_logic(filename)
    # 打印结果
    print(result)